package com.ruoyi.framework.mqtt.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Component
public class HandlerChain {

    private List<MessageHandler> handlers = new ArrayList<>(16);

    @Autowired
    MsgHandler msgHandler;
    @Autowired
    PropertiesReportHandler propertiesReportHandler;
    @Autowired
    ReagentUseHandler reagentUseHandler;
    @Autowired
    ItemTestCountHandler itemTestCountHandler;
    @Autowired
    InstrumentAlarmHandler instrumentAlarmHandler;
    @Autowired
    InstrumentMaintainHandler instrumentMaintainHandler;
    @Autowired
    QueryCalibrationDataHandler queryCalibrationDataHandler;

    @PostConstruct
    public void init() {
        addHandler(msgHandler)
                .addHandler(propertiesReportHandler)
                .addHandler(reagentUseHandler)
                .addHandler(itemTestCountHandler)
                .addHandler(instrumentAlarmHandler)
                .addHandler(instrumentMaintainHandler)
                .addHandler(queryCalibrationDataHandler)
        ;
    }

    public HandlerChain addHandler(AbstractHandler handler) {
        handlers.add(handler);
        return this;
    }

    public void handle(Message message) {
        String topic = (String) message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC);
        String msg = message.getPayload().toString();
        handlers.forEach(r -> r.handleMessage(message, topic, msg));
    }

}